using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.SilverlightControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace arb.SharePoint.SecureSilverlight
{
    [Guid("3dd79f67-cfde-4d78-9889-9f134a7fc2b1")]
    public class SilverlightWebPartHost : WebPart
    {
        public static String Parameters = string.Empty;
        public static String _emailAddress;
        private Silverlight _slc;

        public SilverlightWebPartHost()
        {
            ExportMode = WebPartExportMode.All;
            _emailAddress = EmailAddress;
        }

        public int SlWidth { get; set; }
        public int SlHeight { get; set; }
        public string SlDocLibUrl { get; set; }
        public string SlFile { get; set; }
        public string EmailAddress { get; set; }

        public override EditorPartCollection CreateEditorParts()
        {
            EditorPart logoEditorPart = new SilverlightEditorPart {ID = string.Format("{0}_EditorPart", ID), GroupingText = "Secure Silverlight Configuration"};
            var parts = new List<EditorPart> {logoEditorPart};
            return new EditorPartCollection(parts);
        }

        public override object WebBrowsableObject
        {
            get { return this; }
        }

        public void InsertOrModifyRecordAndHydrateParams()
        {
            if (Page.Request.Url.AbsoluteUri.Contains("?PageView=Shared)"))
            {
                WebPartInstance currentInstance = CreateStronglyTypedWebPartInstanceFromContext();
                bool doesexist = Builders.DoesInstanceExist(currentInstance);
                Builders.ChangeOrInsertAndAppendParams(doesexist, currentInstance);
            }
        }

        public WebPartInstance CreateStronglyTypedWebPartInstanceFromContext()
        {
            SPWeb web = SPContext.Current.Web;
            var instance = new WebPartInstance {RootWebTitle = web.IsRootWeb ? web.Title : SPContext.Current.Site.RootWeb.Title, SilverlightFileBeingUsed = SlFile, PageUrl = Page.Request.Url.AbsoluteUri, PageTitle = SPContext.Current.Item != null ? SPContext.Current.Item["Name"].ToString() : "No Page Title Available", LastModifiedDate = DateTime.Now};
            return instance;
        }

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
                if (scriptManager == null)
                {
                    scriptManager = new ScriptManager();
                    Controls.Add(scriptManager);
                }

                if (string.IsNullOrEmpty(SlDocLibUrl) || string.IsNullOrEmpty(SlFile))
                {
                    Controls.Add(new LiteralControl("This WebPart At Minumum Requires The Document Library And Silverlight File Set. Please Ensure These Properties!"));
                }
                else
                {
                    Parameters = string.Empty;

                    InsertOrModifyRecordAndHydrateParams();
                }
            }
            catch (Exception x)
            {
                Controls.Add(new LiteralControl(string.Format("Error In OnLoad: {0}", x.Message)));
            }
            base.OnLoad(e);
        }


        protected override void RenderContents(HtmlTextWriter writer)
        {
            EnsureChildControls();
            if ((_slc != null))
            {
                _slc.RenderControl(writer);
            }
            base.RenderContents(writer);
        }

        protected override void CreateChildControls()
        {
            try
            {
                _slc = new Silverlight
                           {
                               ID = SlFile + ID,
                               InitParameters = Parameters,
                               Source = string.Format("{0}/{1}", SlDocLibUrl, SlFile),
                               Width = SlWidth,
                               Height = SlHeight
                           };
                Controls.Add(_slc);
            }
            catch (Exception x)
            {
                Controls.Add(new LiteralControl(string.Format("Error In CreateChildControls: {0}", x.Message)));
            }
            base.CreateChildControls();
        }
    }
}